#!/usr/bin/env node
// import fetch from 'node-fetch';
import PropertiesReader from 'properties-reader';
import fs from 'fs';
import path from 'path';
import WebSocket from 'ws';
import readline from 'readline';
import { fetchUserOpsToken } from './vops_user.js';


// 1. 获取当前目录（绝对路径）
const currentDir = process.cwd();
// 获取 Shell 传来的参数
// 这是 解析后
const podName = process.argv[2];
const profile = process.argv[3];
// 2. 计算 ops_global_path
// 逻辑：截断当前路径中 /Documents/ 及后面内容，然后拼接 /Documents/ops/ops_global.properties
const docsIndex = currentDir.indexOf('/Documents/');
if (docsIndex === -1) {
    console.error('【错误】当前路径不包含 /Documents/ 目录，无法确定 ops_global.properties 路径');
    process.exit(1);
}
const basePath = currentDir.substring(0, docsIndex);
const opsGlobalPath = path.join(basePath, 'Documents/ops/ops_global.properties');
// 3. 判断 ops_global_path 是否存在
if (!fs.existsSync(opsGlobalPath)) {
    console.error(`【错误】全局配置文件不存在：${opsGlobalPath}`);
    process.exit(1);
}
const opsGlobal = PropertiesReader(opsGlobalPath);
const opsUser = opsGlobal.get('ops_user');
if (!opsUser) {
    console.error(`【错误】ops_user 未配置或为空，文件路径：${opsGlobalPath}`);
    process.exit(1);
}
const opsPropertiesPath = path.join(currentDir, 'ops.properties');
const opsProps = PropertiesReader(opsPropertiesPath);
const opsName = opsProps.get('project.'+podName+'.opsName');

if (!opsName) {
    console.error(`【错误】ops.properties 文件中缺少 project.hs-ipo-admin.opsName 配置或值为空`);
    process.exit(1);
}
const token = await fetchUserOpsToken(opsUser);
console.log('ops_token:', token);
console.log('ops_user:', opsUser);
console.log('opsName:', opsName);

const headers = {
    'Accept': 'application/json, text/plain, */*',
    'Referer': `https://vops.hszq8.com`,
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
};
console.log(`podName: ${podName}, profile: ${profile}`);

// ===== 这里替换成你的真实 wss 地址、token、cookie =====
// const WS_URL = `wss://vops.hszq8.com/app/api/v1/console/${namespace}/pod_console?key=pod_zgds-k8sluster.hszq8.com:6443_hspt-hk-feature_${pod}_tomcat-xxx&token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTc1NDYxNjE1NywiZXhwIjoxNzU0NjM3NzU3fQ.eyJ1aWQiOjYzNzJ9.SpKdQw63ydKgDzdOL8B4wyhlSzMqvD5x0HDmfanVnEp6UFCCpvIVzZVV584s3I921BdcsfsQL07H2ojEmwqsGw&version=v2`;
const WS_URL = `
wss://vops.hszq8.com/app/api/v1/console/hs_bss_admin_server/pod_console?key=pod_zgds-k8sluster.hszq8.com:6443_hspt-hk-feature_hs-bss-admin-server-hk-feature_hs-bss-admin-server-hk-feature-tomcat-7c55db65d8-cjrgf_10.73.11.52_10.73.226.179&token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTc1NDYxNjE1NywiZXhwIjoxNzU0NjM3NzU3fQ.eyJ1aWQiOjYzNzJ9.SpKdQw63ydKgDzdOL8B4wyhlSzMqvD5x0HDmfanVnEp6UFCCpvIVzZVV584s3I921BdcsfsQL07H2ojEmwqsGw&version=v2`;

const COOKIES = `vops_token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTc1NDYxNjE1NywiZXhwIjoxNzU0NjM3NzU3fQ.eyJ1aWQiOjYzNzJ9.SpKdQw63ydKgDzdOL8B4wyhlSzMqvD5x0HDmfanVnEp6UFCCpvIVzZVV584s3I921BdcsfsQL07H2ojEmwqsGw; lcm_platform=master; session=.eJxdT0luwzAM_AvPhmAtlmSdmnc0QaFYjGtUi2vZ6SHw30v12AsxJGeGwxfIYB5Bjj0KbYw3qPTEtVAjH3DgYpjAvQCTXyI4ePo8Y1wq-yHw9ln3kmc2lQQdJKzVzwiuJ1zuSyQI3Gjba8WtkI1SApLLO3zZSq1fV6pxamoUSLV-xwS3DrJPTX09jLT360G5etquuKUW5pJzOfJEjIePFc8ONkxlxw8fwtaOjoJxbdnYM6Wb6-7TCo6bQWluB6P-RvtRwYkOjiWA09I0WHH7_ySc5y_eLlY2.aJVazg.-Jm4lbd0DwzMAiPEHHzEPc7Xx1I`;

const ws = new WebSocket(WS_URL, {
    headers: {
        Origin: 'https://vops.hszq8.com',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36'
    }
});

ws.on('open', () => {
    console.log('✅ 已连接到远程控制台');
});

ws.on('message', (data) => {
    process.stdout.write(data.toString());
});

ws.on('close', () => {
    console.log('\n❌ 连接已关闭');
    process.exit(0);
});

ws.on('error', (err) => {
    console.error('❌ WebSocket 错误:', err.message);
});

// 捕获键盘输入（原始模式）
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY) {
    process.stdin.setRawMode(true);
}

process.stdin.on('keypress', (str, key) => {
    if (key.sequence === '\u0003') { // Ctrl+C
        console.log('\n🔌 手动断开连接');
        process.exit();
    }
    ws.send(key.sequence);
});
